<template>
  <div class="box">
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="用户管理" name="second">
          <!-- layout布局 -->

          <el-row type="flex" justify="space-between">
            <el-col :span="6"><h4>江苏传智播客教育有限公司</h4></el-col>
            <el-col :span="6" class="right-col">
              <!-- 下拉菜单 -->
              <span class="head">负责人</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>

                <el-dropdown-menu slot="dropdown">
                  <el-button
                    type="text"
                    @click="dialogFormVisible = true"
                  >添加部门</el-button>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <!-- 和底部的内容分割开来 -->
          <el-divider />
          <el-tree
            :data="departs"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <!-- 通过自定义作用域插槽获取数据 -->

            <template #default="{ data }">
              <el-row type="flex" justify="space-between" class="tree-row">
                <el-col :span="6">{{ data.name }}</el-col>
                <el-col :span="6" class="right-col">
                  <!-- 下拉菜单 -->
                  <span class="head">{{ data.manager }}</span>
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="addChildren(data)"
                        >添加子部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="enterEdit(data)"
                        >编辑子部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="deleteChildren(data)"
                        >删除子部门</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 弹框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择活动区域"
            @focus="onFocus"
          >
            <!-- 新增部门,manager用的是名字,不是id 这个label和value都渲染相同的数据 -->
            <el-option
              v-for="item in managers"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentById,
  editDepartment,
  deleteDepartment
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees.js'
export default {
  name: 'Departments',
  data() {
    return {
      // 部门负责人数组
      managers: [],
      // 是否显示弹框
      dialogFormVisible: false,
      // 表单的数据
      form: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      },
      formLabelWidth: '120px',
      activeName: 'second',
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 表单校验规则
      rules: {
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '请填写1-50个字符', trigger: 'change' }
        ],
        manager: [{ required: true, trigger: 'blur' }],
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      // 如果有id 那就是编辑部门  没id就是新增部门
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 删除
    deleteChildren(data) {
      // const res = await deleteDepartment(data.id)
      //    this.$message.success(`删除成功`)
      //     this.getData()
      this.$confirm('确认删除此内容吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '再考虑一下',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteDepartment(data.id)
          this.$message.success(`删除成功`)
          this.getData()
        })
        .catch(() => {})
    },
    // 点击部门中添加子部门
    addChildren(data) {
      console.log(data)
      this.form.pid = data.id
      console.log('form中的pid:--' + this.form.pid)
      this.dialogFormVisible = true
    },
    // 点击取消，重置
    onCancel() {
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      }
      this.dialogFormVisible = false
    },
    // 获取tree数据的方法
    async getData() {
      const res = await getDepartments()
      // console.log('res:', res)

      // 排除掉pid为-1
      const res1 = res.depts.filter((v) => v.pid !== '-1')
      // 找顶级节点 filter 大数组中筛选出若干个你要的值
      const root = res1.filter((v) => v.pid === '')
      // console.log('root:', root)
      // 找后代
      root.forEach((v) => {
        // 获取 子节点
        // pid和当前节点的id相同
        v.children = res1.filter((vc) => vc.pid === v.id)
      })
      // 把处理完毕的数据 设置上去
      this.departs = root
      // 直接去vue的插件看,不会有`...`
      // console.log('root:', root)
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          // 判断是否有id
          // console.log(this.form.id);
          if (this.form.id) {
            // 有id就发起请求    // 修改部门信息
            const resId = await editDepartment(this.form)
            this.$message.success(`修改成功`)
            this.dialogFormVisible = false
            this.getData()
            // 调用清空方法
            this.onCancel()
          } else {
            // 新增
            // 调用接口
            // console.log('res:', res)
            const res = await addDepartments(this.form)
            this.$message.success(`新增成功`)
            this.dialogFormVisible = false
            this.getData()
            // 调用清空方法
            this.onCancel()
          }
        } else {
          this.$message.error('数据格式有误,请检查哦!')
          return false
        }
      })
      // 点击提交，清空表单内容
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      }
    },
    async onFocus() {
      // console.log('123')
      // 调用接口
      const res = await getEmployeeSimple()
      // console.log('res:', res)
      this.managers = res
    },

    // 查看子部门
    async enterEdit(data) {
      // 获取
      const res = await getDepartmentById(data.id)
      this.form = res
      this.dialogFormVisible = true
    },
    handleNodeClick() {}
  }
}
</script>

<style lang="scss" scoped>
.box {
  .box-card {
    .el-row {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }
    .el-col {
      border-radius: 4px;
      h4 {
        margin: 0;
      }
      .head {
        font-size: 14px;
        margin-right: 10px;
      }
    }
    .right-col {
      text-align: right;
    }
  }
  .el-tab-pane {
    padding: 20px;
  }
  .tree-row {
    width: 100%;
  }
}
</style>
